<?php 
namespace Wdl\model;

use Wdl\validate\ValidateException;
use Wdl\helper\FrontHelper;
use Wdl\helper\webHelper;
use Wdl\validate\navmenu;
use Wdl\helper\form_element;
use Wdl\validate\Validate;
class webfront extends base {
  
    public function navmenu()
    {
        //print_r($this->_GPC);
       
        try{
            $validate = new navmenu();
            $data = $validate->check($this->_GPC);

            return $this->msg(0,'', $this->_GPC );

        }catch( ValidateException $e){

            return $this->msg(1, $e->getMessage());
        }

       
    }
    public function config(){
        return $this->msg(0, 'siteinfo', $this->_W);
    }

    public function siteparams()
    {
        $adapter =  include  IA_ROOT. "/addons/kbwdl_shequzufang/vender/adapter.php";
       
        $this->_forms = $adapter['sechouse'];
        $this->other = $adapter['newhouse'];

        $_GPC = $this->_GPC;
        $uniacid = $this->uniacid;
        $uid = $this->uid;
        $openid = $this->openid;  
        $p = [];
        /**/
        $sql = 'SELECT `settings` FROM ' . tablename('uni_account_modules') . ' WHERE `uniacid` = :uniacid AND `module` = :module';
        // $settings = pdo_fetchcolumn($sql, array(':uniacid' => $uniacid, ':module' => 'kbwdl_shequzufang'));
        // $sec =   iunserializer($settings);
        $sec = webHelper::fetch_place_data("setting", 'display');
 
         /* 价格类型 */
         $p['zu_price'] = form_element::_option($sec['search_zhu_price']);
         /*根据类型获取不同价格类型0=二手房2=租房3=新房4=商铺 7=厂房8=仓库9=写字楼
         rent_type 0=出售2=出租3=转让*/
         $_GPC['type'] = $_GPC['zhutype'] * 10 + $_GPC['rent_type'];
         if (intval($_GPC['type'] == 20)) {/*租房*/
             $p['price'] = form_element::_option($sec['search_zhu_price']);
         } elseif ($_GPC['type'] == 10) {/*新房*/
             $p['price'] = form_element::_option($sec['search_newhouse_price']);
         } elseif($_GPC['type'] == 92){ /*写字楼出 租*/
             $p['price'] = form_element::_option($sec['search_xie_sou_price']);
         } elseif($_GPC['type'] == 90){ /*写字楼出售*/
             $p['price'] = form_element::_option($sec['search_xie_zhu_price']);
         } elseif($_GPC['type'] == 40){ /*商铺出售*/
             $p['price'] = form_element::_option($sec['search_sp_sou_price']);
         } elseif($_GPC['type'] == 42){ /*商铺出售*/
             $p['price'] = form_element::_option($sec['search_sp_zhu_price']);
          } elseif($_GPC['type'] == 43){ /*生意转让*/
             $p['price'] = form_element::_option($sec['search_syi_sou_price']);
         }elseif($_GPC['type'] == 80 || $_GPC['type'] == 82 ){ /*厂房仓库出租*/
             $p['price'] = form_element::_option($sec['search_xie_sou_price']);
         } elseif($_GPC['type'] == 70  || $_GPC['type'] == 72){ /*厂房仓库出租*/
             $p['price'] = form_element::_option($sec['search_xie_zhu_price']);
         }else{/*二手房*/
             $p['price'] = form_element::_option($sec['search_sec_price']);
         }
         $p['housetype'] = form_element::_option($this->_forms['housetype']);
         $p['newhouse_tese']= form_element::_option($this->_forms['newhouse_tese']);
         $p['sptype'] = form_element::_option($this->_forms['sptype']);
         $p['chaoxiang'] = form_element::_option($this->_forms['chaoxiang']);
         $p['zhaungxiu'] = form_element::_option($this->_forms['zhaungxiu']);
         $p['disposition'] = form_element::_option($this->_forms['disposition']);
         $p['rent_zhu'] = form_element::_option($this->_forms['rent_zhu']);
         $p['louceng'] = form_element::_option($this->_forms['louceng']);
           /*厂房*/
          $p['rent_changfang'] = form_element::_option($this->_forms['rent_changfang']);
          $p['changfang_type'] = form_element::_option($this->_forms['changfang_type']);
          $p['changfang_jiegou'] = form_element::_option($this->_forms['changfang_jiegou']);
           $p['cangku_used'] = form_element::_option($this->_forms['cangku_used']);
            $p['oldage'] = form_element::_option($this->_forms['oldage']);
          /*仓库类型*/
          $p['cangku_type'] = form_element::_option($this->_forms['cangku_type']);
         /* 行业，行业类型 */
         $p['hangye'] = form_element::_option($this->_forms['hangye']);
         $p['jingyin'] = $this->_forms['jingyin'];
         $p['charges_step']=   form_element::_option($this->_forms['charges_step'],',','|', true);
       
 
         $years = date('Y');
         $start = 1987;
         $p['years']  = array();
         for ($i = 0; $i < ($years - $start); $i++) {
             array_push($p['years'],  $years - $i);
         }
          
         $p['sufix'] = form_element::_option($sec['search_sec_sufix']);
         $p['room'] = array( '一房'=> 1, '两房'=> 2, '三房'=> 3, '四房'=> 4, '四房以上'=> 5);
         $p['mainhouse'] = $this->other['hxtype'];
         $p['order'] = array('默认排序'=>1,'单价由低到高'=>2,'单价由高到低'=>3,'开盘时间顺序'=>4,'开盘时间倒序'=>5);
         $p['housetags']= $this->other['housetags'];
         $p['projectTypes'] = $this->other['projectTypes'];
         $p['opentime'] = $this->other['opentime'];
         /*二手房房屋时间*/
         $p['houseyears'] = array('2年内'=>1,'2-5年'=>2 ,'5-10年'=>3,'10年上'=>4);
         $p['ptype'] = array('个人'=>1,'经纪人'=>2);
         $p['secorder'] = array('发布时间最新'=>1, '更新时间最新'=>2, '价格从高到低'=>3);
         /*租房的类型*/
         $p['zhumethod'] = array('整租'=>1, '合租'=>2);
         $p['zhudays'] = array('年租'=>1, '月租'=>2,'日租'=>3);
         /**
          * 获取列表可用模块
          */
         $ret2 = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=11 and module='kbwdl_shequzufang'");
         $confmenu = iunserializer($ret2['conf_value']);
         $block = array(
           'house_nav_newhouse'=>array( 'name'=> '新房', 'url'=> '../newshop/search', 'opentype'=> 'redirect','tags'=>0 ),
           'house_nav_sec'=> array( 'name'=> '出售', 'url'=> '../house/search?rent=0&zhutype=0', 'opentype'=> 'redirect' ,'tags'=>0),
           'house_nav_zhu'=> array(  'name'=> '租房', 'url'=> '../house/zhu?rent=2&zhutype=2', 'opentype'=> 'redirect','tags'=>1 ),
           'house_nav_xie_zhu'=> array(  'name'=>'写字楼出租', 'url'=> '../house/xie?rent=2&zhutype=1', 'opentype'=> 'redirect' ,'tags'=>2 ),
           'house_nav_xie_sale'=> array(  'name'=> '写字楼出售', 'url'=> '../house/xie?rent=0&zhutype=1', 'opentype'=> 'redirect' ,'tags'=>2 ),
           'house_nav_sp_zhu'=> array(  'name'=> '商铺出租', 'url'=> '../house/sp?rent=2&zhutype=2', 'opentype'=> 'redirect','tags'=>3  ),
           'house_nav_sp_sale'=> array(  'name'=> '商铺出售', 'url'=> '../house/sp?rent=0&zhutype=2', 'opentype'=> 'redirect' ,'tags'=>3 ),
           'house_nav_syi_sale'=>  array( 'name'=> '生意转让', 'url'=> '../house/syi?rent=0&zhutype=3', 'opentype'=>'redirect' ,'tags'=>4 ),
          'house_nav_changfang_sale'=>  array( 'name'=> '厂房出售', 'url'=> '../house/changfang?rent=0&zhutype=7', 'opentype'=>'redirect' ,'tags'=>7 ),
          'house_nav_cangku_sale'=>  array( 'name'=> '仓库出售', 'url'=> '../house/cangku?rent=0&zhutype=8', 'opentype'=>'redirect' ,'tags'=>7 ),
         'house_nav_changfang_zhu'=>  array( 'name'=> '厂房出租', 'url'=> '../house/changfang?rent=2&zhutype=7', 'opentype'=>'redirect' ,'tags'=>8 ),
          'house_nav_cangku_zhu'=>  array( 'name'=> '仓库出租', 'url'=> '../house/cangku?rent=2&zhutype=8', 'opentype'=>'redirect','tags'=>8  )
         
         );
         $navbtn =  array();
         foreach ($block as $key =>$v){
             if( $confmenu[$key] ==1 ){
                 $navbtn[] = $v;
             }
         }
         $p['house_nav_block'] = $navbtn;
         /*end*/
         return $this->msg(0, 'siteparams', $p);
    }

    public function isbroker(){
        global $_W;
        $broker = FrontHelper::get_broker();
        return $this->msg(0, 'ok',  $broker);
         
    }

    public function getbroker()
    {
        global $_GPC;
        if(!empty($_GPC['toopenid'])){
            $broker = FrontHelper::get_broker( $_GPC['toopenid'] ,true);
            return $this->msg(0, 'ok',  $broker);
        }
        $broker = FrontHelper::get_broker( $_GPC['bid'] );
        return $this->msg(0, 'ok',  $broker);
         
    }

    /**
     * 获取首页5条 通知
     */
    public function notice()
    {
        $list = FrontHelper::get_notice_list(5);
        $title = $url = [];
        foreach($list as $item){
            $title[] = $item['title'];
            $url[] = [
               'link'=> !empty($item['gpoun_address']) ? urlencode($item['gpoun_address'])  : "",
                'id'=> $item['id'] 
            ];
        }
        return $this->msg(0, 'notice', ['title'=> $title, 'url'=> $url]);
    }
    /** 
     * 小程序的数据
     */
    public function option()
    {
        global $_W;
        $setting = webHelper::fetch_place_data('setting' );
        //顶部幻灯片数据处理
        foreach($setting['wxapp']['indexslides'] as $k => $v){
            $setting['wxapp']['indexslides'][$k] = tomedia($v);
        }
        //处理封面图
        $setting['wxapp']['send_index_banner'] = tomedia( $setting['wxapp']['send_index_banner'] );
        $setting['wxapp']['send_sell_banner'] = tomedia($setting['wxapp']['send_sell_banner']);
        //处理编辑器数据
        foreach( $setting['company'] as $k => &$item){
             $item = htmlspecialchars_decode($item);
        }
        //空图片
        $setting['wxapp']['photoface'] = tomedia("/addons/kbwdl_shequzufang/style/images/house_face_min.jpg");
        //获取菜单数据
        //0=二手房2=租房3=新房4=商铺 7=厂房8=仓库9=写字楼
        /*默认菜单*/
        $navmenu = [
             0=> array(
                'name'=> '新房',
                'pathurl'=> '/pages/house/house?zhutype=3',
                'icon'=>'icon-dalou',
                'iconpic'=>'',
                'isshow'=>1,
                'order'=>0,
                ),
            1=>  array(
                    'name'=> '二手房',
                    'pathurl'=> '/pages/house/house',
                    'icon'=>'icon-jianyuede',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
            2=>  array(
                    'name'=> '找租房',
                    'pathurl'=> '/pages/house/house?zhutype=2',
                    'icon'=>'icon-zufang',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
            3=>  array(
                    'name'=> '找商铺',
                    'pathurl'=> '/pages/house/house?zhutype=4',
                    'icon'=>'icon-shop-full',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                4=>  array(
                    'name'=> '写字楼',
                    'pathurl'=> '/pages/house/house?zhutype=9',
                    'icon'=>'icon-xiezilou',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                5=>  array(
                    'name'=> '仓库',
                    'pathurl'=> '/pages/house/house?zhutype=8',
                    'icon'=>'icon-zhusu',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                6=>  array(
                    'name'=> '我要出租',
                    'pathurl'=> '/pages/send/sell?type=chuzu',
                    'icon'=>'icon-yijianfankui',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                
                7=>  array(
                    'name'=> '我要卖房',
                    'pathurl'=> '/pages/send/sell?type=chushou',
                    'icon'=>'icon-ziyouanpai',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
               
                8=>  array(
                    'name'=> '求购',
                    'pathurl'=> '/pages/send/index?type=qiugou',
                    'icon'=>'icon-jingjide',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                
                9=>  array(
                    'name'=> '求租',
                    'pathurl'=> '/pages/send/index?type=qiuzu',
                    'icon'=>'icon-shushidu',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                10=>  array(
                    'name'=> '厂房',
                    'pathurl'=> '/pages/house/house?zhutype=7',
                    'icon'=>'icon-gaoduande',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                11=>  array(
                    'name'=> '地图找房',
                    'pathurl'=> '/pages/map/map',
                    'icon'=>'icon-zuobiao',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
                12=>  array(
                    'name'=> '贷款计算',
                    'pathurl'=> '/pages/tools/tools',
                    'icon'=>'icon-icon--',
                    'iconpic'=>'',
                    'isshow'=>1,
                    'order'=>0,
                ),
            ];
     
        //开启置顶首页菜单
        if($setting['wxapp']['defnnavmenus'] ==1){
            //查询用户是否有自定义菜单；
            $uniacid = webHelper::bindUniacid();
            $rs =  pdo_fetchall("SELECT * FROM ".tablename('kbwdl_forums').
            " WHERE uniacid = {$uniacid} and disabled=0 and  type=1 ORDER BY orderid ASC");

            foreach($rs as $menu){
                $m = [
                    'name'=> $menu['fname'],
                    'pathurl'=> $menu['desc'],
                    'icon'=>'',
                    'iconpic'=> tomedia($menu['thumb']),
                    'isshow'=>1,
                    'order'=>1,
                    'target' => $menu['islink'],
                ];
                if(isset($navmenu[ $menu['orderid']]) && 
                $navmenu[ $menu['orderid']]['order'] ==0 ) {                
                    $navmenu[ $menu['orderid']] = $m;
                }else{
                    $navmenu[] = $m;
                }
            }
        }
        
        if(is_array($navmenu)){
            foreach($navmenu as $key =>$val){
                if(empty($val['target']))  
                        $val['target'] = 0;//默认打开访问
                if($val['isshow']==1){
                    $setting['navmenu'][] = $val;
                }
            } 
        }
        //格式化商圈数据
        $setting['areas_quan'] = [];
        if(isset($setting['display']['areas'])) {
            $setting['areas_quan'] = FrontHelper::get_areas_quan($setting['display']['areas']);
        }
        return $this->msg(0, 'options', $setting);
    }

    public function getphone()
    {
        global $_W, $_GPC;
        //旧版本可以通过wx.login得到的session_key进行解密
        //现在微信小程序不再支持，需要每次通过code得到
        // $encrypt_data =  $_GPC['encrypdata'];
        // $iv = $_GPC['ivdata'];
        // $key  =   base64_decode($_SESSION['session_key']);

        // $result = aes_pkcs7_decode($encrypt_data, $key, $iv);        
        // //直接通过加密解密
        // var_dump($result);
        // $result = json_decode($result, true);
        // //if($result)
        //     return $this->msg(0, 'phone_info', $result);
        
        //解密失败，采用api接口获取
         /*获取小程序access_token*/
        load()->classs('wxapp.account');
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '". $_W['uniacid']."'" );       
        $accObj= new \WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );   
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" .$ACCESS_TOKEN;
        $ret = ihttp_post($url, json_encode(['code'=> $_GPC['code']]));
        $ret = json_decode($ret['content'], true);
        if($ret['errorCode']==0){
            //通过api接口获取手机号
            return $this->msg(0, 'phone_info', ['code'=>0, 'data'=> $ret['phone_info']]);
        }else{
            return $this->msg(0, 'phone_info', ['code'=>1 , 'data'=> '']);
        }
       
    }

    /**
     * 
     * 必须要前端提供openid 对应用户是公众号还是小程序的 用户
     * 在公众里面，能通过php 得到openid
     * 在小程序里面，openid是进入小程序就能获取到的；
     * @return array
     */
    public function bindMobile()
    {
        global $_W, $_GPC;
        try {
            Validate::make([
                'mobile' => 'required|mobile',                
            ], [
                'mobile.required'   => '请输入手机号码',                 
            ])->check( $_GPC );
          
        } catch (ValidateException $e) {            
            return $this->msg(1,  $e->getMessage() );
        }
        $mobile = $_GPC['mobile'];
        $code = $_GPC['verycode'];
        if(empty($this->openid)){
            return $this->msg(1, '参数不完整');
        }
        //检查验证码
        load()->model('utility');
		if (!preg_match( '/1[3456789][0-9]{9}$/', $mobile)) {
            return $this->msg(1, '手机号码格式错误') ;
		}
        	
        //小程序安全检测接口
        if(! FrontHelper::checkPostContent( $_GPC)){
            return $this->msg(1, '安全检查失败' );
        }
        //
        //是否开启验证码验证
        $config = webHelper::fetch_place_data('setting','security');
        if(!empty($config['smsverifycode']) && $config['smsverifycode']==1){
            if (!code_verify($this->uniacid, $mobile, $code)) {
                table('uni_verifycode')->where(array('receiver' => $mobile))->delete();
                return $this->msg(1, '验证码错误') ;
            }  
            $broker = pdo_fetch("select * from ".tablename("kbwdl_broker").
                        " where uniacid=:uniacid  and mobile=:mobile order by id asc",
                        [
                            'uniacid' => $this->uniacid,  
                            'mobile' => $mobile
                        ]); 
        }else{
      
            $broker = pdo_fetch("select * from ".tablename("kbwdl_broker").
            " where uniacid=:uniacid  and openid=:openid order by id asc",
            [
                'uniacid' => $this->uniacid,  
                'openid' => $this->openid
            ]); 
        }
	
        //绑定手机号和进行注册
        $save =  [ 'mobile'=> $mobile, 'updated_time'=> TIMESTAMP  ];  
        //上面公共save数据；

        if(!empty($broker)){         
            $id = $broker['id'];  
            pdo_update("kbwdl_broker", $save, array('id'=>$id));
       }else{
            $save['ischecked'] = 1;
            $save['groupid'] = 0;
            $save['openid'] = $this->openid;
            $save['uniacid'] = $this->uniacid;
            $save['ecuid'] = $this->uid;
            $save['avatar'] =  $_W['siteroot'] . 'addons/kbwdl_shequzufang/style/images/get_avatar.png'; ;
            $save['nickname'] = '微信用户';
            $save['created_time'] = TIMESTAMP;           
        
            pdo_insert("kbwdl_broker", $save);  
            $id = pdo_insertid();            
           
        }
        $broker = pdo_fetch("select * from ".tablename("kbwdl_broker"). " where  id='$id'");   
        
        return $this->msg(0, 'success', $broker );
    }
    /**
     * 最后一次浏览的房源
     */
    public function lastview()
    {        
        $uniacid = $this->uniacid;
        $openid = $this->openid;
        $sql = "select * from ".tablename('kbwdl_favorite')." where openid='$openid' and uniacid='$uniacid' order by last_time desc";
        $data =  pdo_fetch($sql);
        if(!empty($data)){
            $data['last_time_label'] =  date('m月d日', $data['last_time'] );

            return $this->msg(0, 'success', $data );
        }
        return $this->msg(0, 'success',  ''); 
    }
    /**
     * 客户发布的委托信息
     */
    public function mydemand()
    {
        FrontHelper::check_login();
        $uniacid = $this->uniacid;
        $openid = $this->openid;        
         /* 分页参数 */
         $page = max(1, $this->_GPC['page']);
         $pagesize = isset( $this->_GPC['pagesize'])? $this->_GPC['pagesize'] : 10;
         $startlimit = ($page - 1) * $pagesize;  
         $condition = " uniacid='$uniacid' and openid='$openid'";
         $sql = "SELECT * FROM " . tablename("kbwdl_demand") . " where $condition  order by id desc limit $startlimit, $pagesize";
         $items = pdo_fetchall($sql);
         if (!empty($items)) {
            $type = ['qiugou'=>'求购','qiuzu'=>'求租','chuzu'=>'出租','chushou'=> '出售'];
             foreach ($items as &$item) {
                $item['feed_time_label'] = date('Y年m月d日', $item['feed_time'] );
                $item['created_time'] =  date('m月d日', $item['created_time'] );
                $type_lable =  isset($type[$item['send_type']]) ?$type[$item['send_type']]:'';
                $item['title'] = sprintf("%s %s,%s 期望价格%s%s",$type_lable, $item['village'], $item['huxing'], $item['price'], $item['price_unit']);
             }
         }
        
        $data['total'] = pdo_fetchcolumn(" select count(*)  from ". tablename("kbwdl_demand") . " where $condition ");
        $data['items'] = $items;
        $data['page'] = $page;
        $data['pagesize'] = $pagesize;
        return $this->msg(0, '发布的需求' , $data);
    }

    public function newsdetail()
    {
        $id = $this->_GPC['id'];
        $data = FrontHelper::getNewsDetail($id, $this->uniacid);
        return $this->msg(0, '发布的需求' , $data);
    }

    public function checklogin()
    {
        FrontHelper::check_login();
        return $this->msg(0, '已经登录' );
    }

    //发送验证码
    public function sendsms()
    {
        /* 
        */
        if(empty($this->openid)){
            return $this->msg(1, '参数错误');
        }
        if(empty($this->_GPC['mobile'])){
            return $this->msg(1, '请输入手机号码');
        }
        $mobile = $this->_GPC['mobile'];
        if (!preg_match( '/1[3456789][0-9]{9}$/', $mobile)) {
			return $this->msg(1, '手机号码格式不正确')  ;
		}
        //记录数据
        $verifycode_table = table('uni_verifycode');
        $row = $verifycode_table->getByReceiverVerifycode($this->uniacid, $mobile, '');
    
        $record = array();
        $code = random(6, true);

        if (!empty($row)) {            
            if ($row['total'] >= 3) {
                return $this->msg(1,  '您的操作过于频繁,请稍后再试');
            }
            $record['total'] = $row['total'] + 1;
        } else {
            $record['uniacid'] = $this->uniacid;
            $record['receiver'] = $mobile;
            $record['total'] = 1;
        }
        $record['verifycode'] = $code;

        if (!empty($row)) {
            pdo_update('uni_verifycode', $record, array('id' => $row['id']));
        } else {
            $record['createtime'] = TIMESTAMP;
            pdo_insert('uni_verifycode', $record);
        }
        //发送
        load()->model('cloud');
        $prepare = cloud_prepare();
        if (is_error($prepare)) {
            return $this->msg(1,  $prepare['message']);
        } 
        $postdata = array('verify_code' =>  $code);
        $result = cloud_sms_send($mobile, '800010', $postdata);
        if (is_error($result)) {
            return $this->msg(1,  $result['message'] );
        }
        return $this->msg(0,  '短信发送成功!');
    }
    
}